package com.googlecode.h0v3rk4rt.net;

import java.io.*;
import java.nio.*;
import java.net.*;

public class NetworkingUtils {

	private static final int UDP_MSG_LENGTH = 40; //each message has 5 doubles
	
	public static DatagramPacket makePacket(double[] dArray) {
		return new DatagramPacket(toByta(dArray),UDP_MSG_LENGTH);
	}
	
	public static DatagramPacket makePacket(double[] dArray, InetAddress dest, int port) {
		return new DatagramPacket(toByta(dArray),UDP_MSG_LENGTH, dest, port);
	}
	
	public static DatagramPacket blankPacket() {
		return new DatagramPacket(new byte[UDP_MSG_LENGTH],UDP_MSG_LENGTH);
	}

	public static double[] getData(DatagramPacket packet) {
		return toDoublea(packet.getData());
	}
	
	//Converts a double array into a byte array (so it can be sent on a packet)
	private static byte[] toByta(double[] dArray) {
		ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
		DataOutputStream datastream = new DataOutputStream(bytestream);
		try {
			for (double d : dArray) datastream.writeDouble(d);
			datastream.flush();
		} catch(IOException e) {
			e.printStackTrace();
		}
		return bytestream.toByteArray();
	}
	
	//Converts a byte array into a double array (so it can be read from a packet)
	private static double[] toDoublea(byte[] bArray) {
		double[] dArray = new double[bArray.length/8];
		ByteBuffer.wrap(bArray).asDoubleBuffer().get(dArray);
		return dArray;
	}
}